<?php

namespace control;
/*
*项目核算余额表类
*/

class projectBalanceClass extends adIndexClass
{
    private const page  = 'projectBalance';
    private const title = '项目核算余额表';
    public static bool $isFormat = false;//是否格式化数字

    private function js()
    {
        return <<<eof
<script>
   function changeTableStyle(e){
       let val = e.value;
       $.post(root+'control/adIndex.html?cla=projectBalance&fun=changeTableStyle',{style:val},function(res) {
            if (res.warn==2){
                location.reload();
            }else{
                msg(res.warn,'error')
            }
       },'json')
   }
</script>
eof;
    }

    /**
     * 查询表单
     *
     * @param string $workFlow
     * @return string
     */
    public function homeForm(string $workFlow): string
    {
        //生成查询表单
        switch ($workFlow) {
            case '客户':
                $option = [
                    '客户' => clientProfileClass::kehuSelect(array('title' => '', 'class' => 'width200', 'fun' => 'getClientNameAndCode'))
                ];
                break;
            case '供应商':
                $option = [
                    '供应商' => supplierClass::supplierSelect(['fun' => 'getSupplier', 'class' => 'width200', 'title' => ''])
                ];
                break;
            case '员工':
                $option = [
                    '员工' => selectMultiple(array('name' => 'staffId', 'field' => "concat(orderNo,name) as name,stid", 'table' => 'staff', 'where' => "1=1 order by orderNo asc", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200'))
                ];
                break;
            case '部门':
                $option = [
                    '部门' => selectMultiple(array('name' => 'departmentId', 'field' => "concat(orderNo,name) as name,id", 'table' => 'department', 'where' => "1=1 order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200'))
                ];
                break;
            case '存货':
                $option = [
                    '存货名称' => text(array('name' => 'materialName', 'id' => 'materialId')) .
                        hidden(array('name' => 'materialId', 'value' => '')) .
                        <<<eof
<script>
$("#materialId").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=voucherEdit&fun=getMaterial',
    callback:function(data,e){
       e.siblings("input[name='materialId']").val(data.id)
}}) 
</script>
eof
                ];
                break;
            case '现金流':
                $option = [
                    '现金流' => selectMultiple(array('name' => 'cashId', 'field' => "concat(code,name) as name,id", 'table' => 'cash', 'where' => "coid='" . self::$coid . "' order by code asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200'))
                ];
                break;
            case '项目':
                $option = [
                    '项目' => selectMultiple(array('name' => 'projectId', 'field' => "concat(orderNo,name) as name,id", 'table' => 'project', 'where' => "coid='" . self::$coid . "' order by orderNo asc", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200'))
                ];
                break;
            default:
                $option = [];
        }

        $maxDate = accountDetailsClass::getMaxDate();
        $minDate = accountDetailsClass::getMinDate();
        $array = [
            [
                array_merge($option,[
                    "会计期间" => text(array(
                        "name" => "createTime",
                        'class' => 'width200',
                        'value' => static::rGet(self::$stid .self::$coid. 'SearchMonth') ?: date('Y-m', strtotime($maxDate)) . ' ~ ' . date('Y-m', strtotime($maxDate)),
                        'laydate' => ['type' => 'month', 'range' => '~', 'min' => "'{$minDate}'", 'max' => "'{$maxDate}'"]
                    )),
                    "科目"   => componentClass::subjectSelect(),
                ])
            ]
        ];
        return $this->tableShow($array,1);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('客户');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        $button = $this->buttonGroup('projectBalance');
        return $this->homeFun($this->searchExecute([
            'html' => $html,
            'layout' => 'pop',
            'toolButton' => $button,
            'option' => '{fixed:true, row:2}'
        ]));
    }

    /*列表-查询条件*/
    private function buttonGroup($page = 'projectBalance')
    {
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        $button .= "<select class='select' style='margin-left: 8px' onchange='changeTableStyle(this)'>" . option(array('value' => static::rGet(self::page . 'tableStyle'), 'option' => accountDetailsClass::styleOption)) . "</select>";
        return $button;
    }

    /**
     * 获取样式
     * @return string
     */
    private function getStyle(): string
    {
        $style = static::rGet(self::page . 'tableStyle');
        if (empty($style)) {
            static::rSet(self::page . 'tableStyle', accountDetailsClass::styleOption[0]);
            $style = accountDetailsClass::styleOption[0];
        }
        static::rSet(self::page . 'tableStyle', $style);
        return $style;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        static::rSet(self::$stid .self::$coid. 'SearchMonth', $this->post('createTime'));;
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('客户'),
            '数量金额式' => $this->moneyAndNumSearch('客户'),
        };
        return json_encode($json, 320);
    }

    /**
     * 数量金额式
     */
    public function moneyAndNumSearch($workFlow)
    {
        $and = "";
        switch ($workFlow) {
            case '客户':
                $and .= " and b.khid !=''";
                if ($this->post('khid')) {
                    $and .= " and b.khid = '" . $this->post('khid') . "'";
                }
                break;
            case '供应商':
                $and .= " and b.supplierId !=''";
                if ($this->post('supplierId')) {
                    $and .= " and b.supplierId = '" . $this->post('supplierId') . "'";
                }
                break;
            case '员工':
                $and .= " and b.staffId !=''";
                if ($this->post('staffId')) {
                    $and .= " and b.staffId = '" . $this->post('staffId') . "'";
                }
                break;
            case '部门':
                $and .= " and b.departmentId !=''";
                if ($this->post('departmentId')) {
                    $and .= " and b.departmentId = '" . $this->post('departmentId') . "'";
                }
                break;
            case '存货':
                $and .= " and b.materialId !=''";
                if ($this->post('materialId')) {
                    $and .= " and b.materialId = '" . $this->post('materialId') . "'";
                }
                break;
            case '现金流':
                $and .= " and cashId !=''";
                if ($this->post('cashId')) {
                    $and .= " and cashId = '" . $this->post('cashId') . "'";
                }
                break;
            case '项目':
                $and .= " and b.projectId !=''";
                if ($this->post('projectId')) {
                    $and .= " and b.projectId = '" . $this->post('projectId') . "'";
                }
                break;
        }

        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $endMonth   = end($arr);
        //获取查询结果
        $page = match ($workFlow) {
            '客户' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join kehu as k on k.khid = b.khid  where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.khid,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join kehu as k on k.khid = b.khid ",
                'field'   => 'b.khid,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by orderNo asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '供应商' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join supplier as k on k.id = b.supplierId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.supplierId,k.code from subject as a join subject_assist as b on a.id = b.orderId join supplier as k on k.id = b.supplierId",
                'field'   => 'b.supplierId,k.code',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by code asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '员工' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join staff as k on k.stid = b.staffId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.staffId,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join staff as k on k.stid = b.staffId",
                'field'   => 'b.staffId,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by orderNo asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '部门' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join department as k on k.id = b.departmentId  where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.departmentId,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join department as k on k.id = b.departmentId",
                'field'   => 'b.departmentId,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by orderNo asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '存货' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join material as ma on ma.id = b.materialId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.materialId,ma.code from subject as a join subject_assist as b on a.id = b.orderId join material as ma on ma.id = b.materialId",
                'field'   => 'b.materialId,ma.code',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by code",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '现金流' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join cash as k on k.id = b.cashId  where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  $and UNION select b.cashId,k.code from subject as a join subject_assist as b on a.id = b.orderId join cash as k on k.id = b.cashId",
                'field'   => 'b.cashId,k.code',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by code asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '项目' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join project as k on k.id = b.projectId  where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.projectId,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join project as k on k.id = b.projectId ",
                'field'   => 'b.projectId,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by orderNo asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
        };
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));
        static::rSet(self::$stid . self::page . 'workFlow', $workFlow);
        static::rSet(self::$stid . self::page . 'subjectId', $this->post('subjectId'));
        $tr             = '';
        self::$isFormat = true;
        foreach ($page['array'] as $array) {
            switch ($workFlow) {
                case '客户':
                    $kehu        = query('kehu', "khid = '$array[khid]'");
                    $orderNo     = $kehu['orderNo'];
                    $companyName = $kehu['companyName'];
                    break;
                case '供应商':
                    $supplier    = query('supplier', "id = '$array[supplierId]'");
                    $orderNo     = $supplier['code'];
                    $companyName = $supplier['name'];
                    break;
                case '项目':
                    $project     = query('project', "id = '$array[projectId]'");
                    $orderNo     = $project['orderNo'];
                    $companyName = $project['name'];
                    break;
                case '存货':
                    $material    = query('material', "id = '$array[materialId]'");
                    $orderNo     = $material['code'];
                    $companyName = $material['name'] . '-' . $material['model'];
                    break;
                case '现金流':
                    $cash        = query('cash', "id = '$array[cashId]'");
                    $orderNo     = $cash['code'];
                    $companyName = $cash['name'];
                    break;
                case '部门':
                    $department  = query('department', "id = '$array[departmentId]'");
                    $orderNo     = $department['orderNo'];
                    $companyName = $department['name'];
                    break;
                case '员工':
                    $staff       = query('staff', "stid = '$array[staffId]'");
                    $orderNo     = $staff['orderNo'];
                    $companyName = $staff['name'];
                    break;
                default:
                    $orderNo     = '';
                    $companyName = '';
                    break;
            }

            $targetId    = match ($workFlow) {
                '客户' => $array['khid'],
                '供应商' => $array['supplierId'],
                '员工' => $array['staffId'],
                '部门' => $array['departmentId'],
                '存货' => $array['materialId'],
                '现金流' => $array['cashId'],
                '项目' => $array['projectId'],
            };
            $initResult  = $this->initMoney($workFlow, $targetId, $startMonth, $this->post('subjectId'));
            $monthResult = $this->monthBalance($workFlow, $targetId, $startMonth, $endMonth, $this->post('subjectId'));
            $balance     = $this->balance($workFlow, $targetId, $endMonth, $this->post('subjectId'));
            $tr          .= <<<eof
                     <tr>
                        <td>$orderNo</td>
                        <td>$companyName</td>
                        <td>{$initResult['jieNum']}</td>
                        <td>{$initResult['jiePrice']}</td>
                        <td>{$initResult['jieMoney']}</td>
                        <td>{$initResult['daiNum']}</td>
                        <td>{$initResult['daiPrice']}</td>
                        <td>{$initResult['daiMoney']}</td>
                        <td>{$monthResult['jieNum']}</td>
                        <td>{$monthResult['jiePrice']}</td>
                        <td>{$monthResult['jieMoney']}</td>
                        <td>{$monthResult['daiNum']}</td>
                        <td>{$monthResult['daiPrice']}</td>
                        <td>{$monthResult['daiMoney']}</td>
                        <td>{$balance['jieNum']}</td>
                        <td>{$balance['jiePrice']}</td>
                        <td>{$balance['jieMoney']}</td>
                        <td>{$balance['daiNum']}</td>
                        <td>{$balance['daiPrice']}</td>
                        <td>{$balance['daiMoney']}</td>
                     </tr>
eof;
        }
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html = <<<eof
<table class="tableMany">
    <thead>
        <tr>
            <td rowspan="3" style="vertical-align: middle">辅助核算编码</td>
            <td rowspan="3" style="vertical-align: middle">辅助核算名称</td>
            <td colspan="6" class="center">期初余额</td>
            <td colspan="6" class="center">本期发生额</td>
            <td colspan="6" class="center">期末余额 {$monthSelector['button']}</td>
        </tr>
        <tr>
            <td colspan="3" class="center">借方</td>
            <td colspan="3" class="center">贷方</td>
            <td colspan="3" class="center">借方</td>
            <td colspan="3" class="center">贷方</td>
            <td colspan="3" class="center">借方</td>
            <td colspan="3" class="center">贷方</td>
        </tr>
        <tr>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
            <td>数量</td>
            <td>单价</td>
            <td>金额</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->moneyAndNumStyle() .
            $this->js() .
            $page['button'] .
            clear;
    }

    /**
     * @return string
     */
    public function moneyAndNumStyle(): string
    {
        return <<<eof
<style>
.tableMany thead tr:nth-of-type(2),.tableMany thead tr:nth-of-type(3) {  
    background-color: #f2f2f2;
    color: #555;  
}
</style>
eof;
    }

    /**
     * 金额式
     */
    public function onlyMoneySearch($workFlow): string
    {
        $and = "";
        switch ($workFlow) {
            case '客户':
                $and .= " and b.khid !=''";
                if ($this->post('khid')) {
                    $and .= " and b.khid = '" . $this->post('khid') . "'";
                }
                break;
            case '供应商':
                $and .= " and b.supplierId !=''";
                if ($this->post('supplierId')) {
                    $and .= " and b.supplierId = '" . $this->post('supplierId') . "'";
                }
                break;
            case '员工':
                $and .= " and b.staffId !=''";
                if ($this->post('staffId')) {
                    $and .= " and b.staffId = '" . $this->post('staffId') . "'";
                }
                break;
            case '部门':
                $and .= " and b.departmentId !=''";
                if ($this->post('departmentId')) {
                    $and .= " and b.departmentId = '" . $this->post('departmentId') . "'";
                }
                break;
            case '存货':
                $and .= " and b.materialId !=''";
                if ($this->post('materialId')) {
                    $and .= " and b.materialId = '" . $this->post('materialId') . "'";
                }
                break;
            case '现金流':
                $and .= " and b.cashId !=''";
                if ($this->post('cashId')) {
                    $and .= " and b.cashId = '" . $this->post('cashId') . "'";
                }
                break;
            case '项目':
                $and .= " and b.projectId !=''";
                if ($this->post('projectId')) {
                    $and .= " and b.projectId = '" . $this->post('projectId') . "'";
                }
                break;
        }
        $arr        = $this->post('createTime') ? explode(' ~ ', $this->post('createTime')) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
        $startMonth = trim($arr[0]);
        $endMonth   = end($arr);
        //获取查询结果
        //获取查询结果
        $page = match ($workFlow) {
            '客户' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join kehu as k on k.khid = b.khid  where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  $and UNION select b.khid,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join kehu as k on k.khid = b.khid",
                'field'   => 'b.khid,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by orderNo asc",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' $and  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '供应商' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join supplier as k on k.id = b.supplierId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.supplierId,k.code from subject as a join subject_assist as b on a.id = b.orderId join supplier as k on k.id = b.supplierId",
                'field'   => 'b.supplierId,k.code',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 $and order by code",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' $and  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '员工' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join staff as k on k.stid = b.staffId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.staffId,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join staff as k on k.stid = b.staffId",
                'field'   => 'b.staffId,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 {$and} order by orderNo",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '部门' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join department as k on k.id = b.departmentId  where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.departmentId,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join department as k on k.id = b.departmentId",
                'field'   => 'b.departmentId,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 {$and} order by orderNo",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '存货' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join material as ma on ma.id = b.materialId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.materialId,ma.code from subject as a join subject_assist as b on a.id = b.orderId join material as ma on ma.id = b.materialId",
                'field'   => 'b.materialId,ma.code',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 {$and} order by code",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '现金流' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join cash as k on k.id = b.cashId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.cashId,k.code from subject as a join subject_assist as b on a.id = b.orderId join cash as k on k.id = b.cashId",
                'field'   => 'b.cashId,k.code',
                "where"   => "a.coid = '" . self::$coid . "'  and b.initMoney !=0 {$and} order by code",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
            '项目' => $this->page([
                "table"   => "subject as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id join project as k on k.id = b.projectId where a.coid = '" . self::$coid . "' and c.isTemplate = '否'  {$and} UNION select b.projectId,k.orderNo from subject as a join subject_assist as b on a.id = b.orderId join project as k on k.id = b.projectId",
                'field'   => 'b.projectId,k.orderNo',
                "where"   => "a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and} order by orderNo",
                'pageNum' => 50,
                'union'   => "select ifnull(count(a.id),0) as num from subject  as a join voucher_detail as b on a.id = b.subjectId join voucher as c on b.orderId =c.id  where a.coid = '" . self::$coid . "' and c.isTemplate = '否' {$and}  UNION select ifnull(count(a.id),0) as num from subject as a join subject_assist as b on a.id = b.orderId where a.coid = '" . self::$coid . "' and b.initMoney !=0 {$and}",
            ]),
        };
        static::rSet(self::$stid . self::page . 'sql', $page['fullSql']);
        static::rSet(self::$stid . self::page . 'subjectId', $this->post('subjectId'));
        static::rSet(self::$stid . self::page . 'time', $this->post('createTime'));
        static::rSet(self::$stid . self::page . 'workFlow', $workFlow);

        self::$isFormat = true;
        $tr             = '';
        foreach ($page['array'] as $array) {
            switch ($workFlow) {
                case '客户':
                    $kehu        = query('kehu', "khid = '$array[khid]'");
                    $orderNo     = $kehu['orderNo'];
                    $companyName = $kehu['companyName'];
                    break;
                case '供应商':
                    $supplier    = query('supplier', "id = '$array[supplierId]'");
                    $orderNo     = $supplier['code'];
                    $companyName = $supplier['name'];
                    break;
                case '项目':
                    $project     = query('project', "id = '$array[projectId]'");
                    $orderNo     = $project['orderNo'];
                    $companyName = $project['name'];
                    break;
                case '存货':
                    $material    = query('material', "id = '$array[materialId]'");
                    $orderNo     = $material['code'];
                    $companyName = $material['name'] . '-' . $material['model'];
                    break;
                case '现金流':
                    $cash        = query('cash', "id = '$array[cashId]'");
                    $orderNo     = $cash['code'];
                    $companyName = $cash['name'];
                    break;
                case '部门':
                    $department  = query('department', "id = '$array[departmentId]'");
                    $orderNo     = $department['orderNo'];
                    $companyName = $department['name'];
                    break;
                case '员工':
                    $staff       = query('staff', "stid = '$array[staffId]'");
                    $orderNo     = $staff['orderNo'];
                    $companyName = $staff['name'];
                    break;
                default:
                    $orderNo     = '';
                    $companyName = '';
                    break;
            }

            $targetId    = match ($workFlow) {
                '客户' => $array['khid'],
                '供应商' => $array['supplierId'],
                '员工' => $array['staffId'],
                '部门' => $array['departmentId'],
                '存货' => $array['materialId'],
                '现金流' => $array['cashId'],
                '项目' => $array['projectId'],
            };
            $initResult  = $this->initMoney($workFlow, $targetId, $startMonth, $this->post('subjectId'));
            $monthResult = $this->monthBalance($workFlow, $targetId, $startMonth, $endMonth, $this->post('subjectId'));
            $balance     = $this->balance($workFlow, $targetId, $endMonth, $this->post('subjectId'));
            $tr          .= <<<eof
                     <tr>
                        <td>$orderNo</td>
                        <td>$companyName</td>
                        <td>{$initResult['jieMoney']}</td>
                        <td>{$initResult['daiMoney']}</td>
                        <td>{$monthResult['jieMoney']}</td>
                        <td>{$monthResult['daiMoney']}</td>
                        <td>{$balance['jieMoney']}</td>
                        <td>{$balance['daiMoney']}</td>
                     </tr>
eof;
        }
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',$arr));
        $html = <<<eof
<table class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align: middle">辅助核算编码</td>
            <td rowspan="2" style="vertical-align: middle">辅助核算名称</td>
            <td colspan="2" class="center">期初余额</td>
            <td colspan="2" class="center">本期发生额</td>
            <td colspan="2" class="center">期末余额 {$monthSelector['button']}</td>
        </tr>
        <tr>
            <td>借方</td>
            <td>贷方</td>
            <td>借方</td>
            <td>贷方</td>
            <td>借方</td>
            <td>贷方</td>
        </tr>
    </thead>
    <tbody>
       $tr
    </tbody>
</table>
eof;
        //返回
        return $page['hint'] .
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $html .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->onlyMoneyStyle() .
            $this->js() .
            $page['button'] .
            clear;
    }
    /**
     * @return string
     */
    public function onlyMoneyStyle(): string
    {
        return <<<eof
<style>
.tableMany thead tr:nth-of-type(2) {  
    background-color: #f2f2f2;
    color: #555;  
}
</style>
eof;
    }

    /**
     * 修改列表样式
     * @return bool|string
     */
    public function changeTableStyle(): bool|string
    {
        $style = $this->post('style');

        if (!in_array($style, accountDetailsClass::styleOption)) {
            $json['warn'] = '请选择列表样式';
        } else {
            $json['warn'] = 2;
            static::rSet(self::page . 'tableStyle', $style);
        }
        return json_encode($json, 320);
    }

    /**
     * 期初余额
     * @param $type
     * @param $targetId
     * @param $startMonth
     * @param $subjectId
     * @return array
     */
    public function initMoney($type, $targetId, $startMonth, $subjectId): array
    {
        $where        = match ($type) {
            '客户' => " and khid = '$targetId'",
            '员工' => " and staffId = '$targetId'",
            '供应商' => " and supplierId = '$targetId'",
            '存货' => " and materialId = '$targetId'",
            '现金流' => " and cashId = '$targetId'",
            '部门' => " and departmentId = '$targetId'",
            '项目' => " and projectId = '$targetId'",
            default => ' and 1!=1'
        };
        $assistWhere  = '';
        $voucherWhere = '';
        if ($subjectId) {
            $assistWhere  .= " and a.orderId = '$subjectId'";
            $voucherWhere .= " and subjectId = '$subjectId'";
        }
        //期初金额
        $jieInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '借' and a.coid = '" . self::$coid . "'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
        $daiInit = find(array('table' => "subject_assist as a join subject as b on a.orderId = b.id", 'single' => "b.direction = '贷' and a.coid = '" . self::$coid . "'" . $where . $assistWhere, 'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"));
        //凭证
        $jieVoucher          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where));
        $daiVoucher          = find(array("table" => "voucher as a join voucher_detail as b on a.id = b.orderId", 'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num", "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') < '$startMonth'" . $where));
        $jieVoucher['money'] = self::centToYuan($jieVoucher['money']) + $jieInit['money'];
        $daiVoucher['money'] = self::centToYuan($daiVoucher['money']) + $daiInit['money'];
        $jieVoucher['num']   += $jieInit['num'];
        $daiVoucher['num']   += $daiInit['num'];

        if ($jieVoucher['money'] == $daiVoucher['money'] && ($jieVoucher['money'] == 0)) {
            $jieMoney = 0;
            $daiMoney = 0;
            $balance  = 0;
        } elseif ($jieVoucher['money'] > $daiVoucher['money']) {
            $jieMoney = $balance = $jieVoucher['money'] - $daiVoucher['money'];
            $daiMoney = 0;
        } else {
            $jieMoney = 0;
            $daiMoney = $balance = $daiVoucher['money'] - $jieVoucher['money'];
        }

        if ($jieVoucher['num'] > $daiVoucher['num']) {
            $jieNum = $jieVoucher['num'] - $daiVoucher['num'];
            $daiNum = 0;
        } else {
            $daiNum = $daiVoucher['num'] - $jieVoucher['num'];
            $jieNum = 0;
        }
        $result = [
            'jieNum'   => voucherEditClass::formatZero($jieNum),
            'jiePrice' => accountDetailsClass::division($balance, $jieNum),
            'daiPrice' => accountDetailsClass::division($balance, $daiNum),
            'daiNum'   => voucherEditClass::formatZero($daiNum),
            'jieMoney' => round($jieMoney, 2),
            'daiMoney' => round($daiMoney, 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }


    /**
     * 本期合计
     */
    public function monthBalance($type, $targetId, $startMonth, $endMonth, $subjectId): array
    {
        $where        = match ($type) {
            '客户' => " and b.khid = '$targetId'",
            '员工' => " and b.staffId = '$targetId'",
            '供应商' => " and b.supplierId = '$targetId'",
            '存货' => " and b.materialId = '$targetId'",
            '现金流' => " and b.cashId = '$targetId'",
            '部门' => " and b.departmentId = '$targetId'",
            '项目' => " and b.projectId = '$targetId'",
            default => ' and 1!=1'
        };
        $voucherWhere = '';
        if ($subjectId) {
            $voucherWhere .= " and subjectId = '$subjectId'";
        }
        $jieInit          = find(array(
            "table" => "voucher as a join voucher_detail as b on a.id = b.orderId",
            'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num",
            "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '借' and date_format(a.recordDate,'%Y-%m') >= '$startMonth' and date_format(a.recordDate,'%Y-%m') <= '$endMonth'" . $where
        ));
        $daiInit          = find(array(
            "table" => "voucher as a join voucher_detail as b on a.id = b.orderId",
            'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num",
            "single" => "a.isTemplate = '否' and a.coid = '" . self::$coid . "' $voucherWhere and b.direction = '贷' and date_format(a.recordDate,'%Y-%m') >= '$startMonth' and date_format(a.recordDate,'%Y-%m') <= '$endMonth'" . $where
        ));
        $jieInit['money'] = self::centToYuan($jieInit['money']);
        $daiInit['money'] = self::centToYuan($daiInit['money']);
        $result           = [
            'jieNum'   => voucherEditClass::formatZero($jieInit['num']),
            'jiePrice' => accountDetailsClass::division($jieInit['money'], $jieInit['num']),
            'daiPrice' => accountDetailsClass::division($daiInit['money'], $daiInit['num']),
            'daiNum'   => voucherEditClass::formatZero($daiInit['num']),
            'jieMoney' => round($jieInit['money'], 2),
            'daiMoney' => round($daiInit['money'], 2)
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /**
     * 计算余额
     * @param $type
     * @param $targetId
     * @param $endMonth
     * @param $subjectId
     * @return array
     */
    public function balance($type, $targetId, $endMonth, $subjectId): array
    {
        $where        = match ($type) {
            '客户' => " and khid = '$targetId'",
            '员工' => " and staffId = '$targetId'",
            '供应商' => " and supplierId = '$targetId'",
            '存货' => " and materialId = '$targetId'",
            '现金流' => " and cashId = '$targetId'",
            '部门' => " and departmentId = '$targetId'",
            '项目' => " and projectId = '$targetId'",
            default => ' and 1!=1'
        };
        $assistWhere  = '';
        $voucherWhere = '';
        if ($subjectId) {
            $assistWhere  .= " and a.orderId = '$subjectId'";
            $voucherWhere .= " and subjectId = '$subjectId'";
        }
        //期初金额
        $jieInit = find(array(
            'table' => "subject_assist as a join subject as b on a.orderId = b.id",
            'single' => "b.direction = '借' and a.coid = '" . self::$coid . "'" . $where . $assistWhere,
            'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"
        ));
        $daiInit = find(array(
            'table' => "subject_assist as a join subject as b on a.orderId = b.id",
            'single' => "b.direction = '贷' and a.coid = '" . self::$coid . "'" . $where . $assistWhere,
            'field' => "ifnull(sum(a.initMoney),0) as money,ifnull(sum(a.initNum),0) as num"
        ));


        $jievoucher          = find(array(
            "table" => "voucher as a join voucher_detail as b on a.id = b.orderId",
            'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num",
            "single" => "a.isTemplate = '否' $voucherWhere and a.coid = '" . self::$coid . "' and b.direction = '借' and date_format(a.recordDate,'%Y-%m') <= '$endMonth'" . $where
        ));
        $daivoucher          = find(array(
            "table" => "voucher as a join voucher_detail as b on a.id = b.orderId",
            'field' => "ifnull(sum(b.money),0) as money,ifnull(sum(b.voucherNum),0) as num",
            "single" => "a.isTemplate = '否' $voucherWhere and a.coid = '" . self::$coid . "' and b.direction = '贷' and  date_format(a.recordDate,'%Y-%m') <= '$endMonth'" . $where
        ));
        $jievoucher['money'] = self::centToYuan($jievoucher['money']) + $jieInit['money'];
        $daivoucher['money'] = self::centToYuan($daivoucher['money']) + $daiInit['money'];
        if ($jievoucher['money'] > $daivoucher['money']) {
            $jieMoney = $jievoucher['money'] - $daivoucher['money'];
            $daiMoney = 0;
        } else {
            $jieMoney = 0;
            $daiMoney = abs($jievoucher['money'] - $daivoucher['money']);

        }
        $balance           = $jievoucher['money'] - $daivoucher['money'];
        $jievoucher['num'] += $jieInit['num'];
        $daivoucher['num'] += $daiInit['num'];
        if ($jievoucher['num'] > $daivoucher['num']) {
            $jieNum = $jievoucher['num'] - $daivoucher['num'];
            $daiNUm = 0;
        } else {
            $daiNUm = abs($jievoucher['num'] - $daivoucher['num']);
            $jieNum = 0;
        }
        $result = [
            'jieNum'   => voucherEditClass::formatZero($jieNum),
            'daiNum'   => voucherEditClass::formatZero($daiNUm),
            'jiePrice' => accountDetailsClass::division($jieMoney, $jieNum),
            'daiPrice' => accountDetailsClass::division($daiMoney, $daiNUm),
            'jieMoney' => round($jieMoney, 2),
            'daiMoney' => round($daiMoney, 2),
            'balance'  => round($balance, 2),
        ];
        if (self::$isFormat) {
            $result = accountDetailsClass::formatArrayNumber($result);
        }
        return $result;
    }

    /*列表页-查询条件*/
    public function supplierOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('供应商');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function supplier()
    {
        $html = $this->supplierOptions(false);
        $button = $this->buttonGroup('projectBalanceSupplier');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function supplierSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('供应商'),
            '数量金额式' => $this->moneyAndNumSearch('供应商'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function staffOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('员工');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function staff()
    {
        $html = $this->staffOptions(false);
        $button = $this->buttonGroup('projectBalanceStaff');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function staffSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('员工'),
            '数量金额式' => $this->moneyAndNumSearch('员工'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function departmentOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('部门');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function department()
    {
        $html = $this->departmentOptions(false);
        $button = $this->buttonGroup('projectBalanceDepartment');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function departmentSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('部门'),
            '数量金额式' => $this->moneyAndNumSearch('部门'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function materialOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('存货');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function material()
    {
        $html = $this->materialOptions(false);
        $button = $this->buttonGroup('projectBalanceMaterial');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function materialSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('存货'),
            '数量金额式' => $this->moneyAndNumSearch('存货'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function cashOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('现金流');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function cash()
    {
        $html = $this->cashOptions(false);
        $button = $this->buttonGroup('projectBalanceCash');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function cashSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('现金流'),
            '数量金额式' => $this->moneyAndNumSearch('现金流'),
        };
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function projectOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->homeForm('项目');
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function project()
    {
        $html = $this->projectOptions(false);
        $button = $this->buttonGroup('projectBalanceProject');
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function projectSearch()
    {
        $style        = $this->getStyle();
        $json['html'] = match ($style) {
            '金额式' => $this->onlyMoneySearch('项目'),
            '数量金额式' => $this->moneyAndNumSearch('项目'),
        };
        return json_encode($json, 320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power($this->post('page'), 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $tr         = [];
            $sql        = static::rGet(self::$stid . self::page . 'sql');
            $style      = $this->getStyle();
            $workFlow   = static::rGet(self::$stid . self::page . 'workFlow');
            $time       = static::rGet(self::$stid . self::page . 'time');
            $subjectId  = static::rGet(self::$stid . self::page . 'subjectId');
            $arr        = $time ? explode(' ~ ', $time) : [date('Y-m', strtotime(accountDetailsClass::getMinDate())), date('Y-m', strtotime(accountDetailsClass::getMaxDate()))];
            $startMonth = trim($arr[0]);
            $endMonth   = end($arr);
            if ($style == '金额式') {
                $title = array("辅助核算编码", "辅助核算名称", "借方期初余额", "贷方期初余额", '借方本期发生额', '贷方本期发生额', '借方期末余额', '贷方期末余额');
                //获取查询结果
                $all = sqlFind($sql);
                foreach ($all as $array) {
                    switch ($workFlow) {
                        case '客户':
                            $kehu        = query('kehu', "khid = '$array[khid]'");
                            $orderNo     = $kehu['orderNo'];
                            $companyName = $kehu['companyName'];
                            break;
                        case '供应商':
                            $supplier    = query('supplier', "id = '$array[supplierId]'");
                            $orderNo     = $supplier['code'];
                            $companyName = $supplier['name'];
                            break;
                        case '项目':
                            $project     = query('project', "id = '$array[projectId]'");
                            $orderNo     = $project['orderNo'];
                            $companyName = $project['name'];
                            break;
                        case '存货':
                            $material    = query('material', "id = '$array[materialId]'");
                            $orderNo     = $material['code'];
                            $companyName = $material['name'] . '-' . $material['model'];
                            break;
                        case '现金流':
                            $cash        = query('cash', "id = '$array[cashId]'");
                            $orderNo     = $cash['orderNo'];
                            $companyName = $cash['name'];
                            break;
                        case '部门':
                            $department  = query('department', "id = '$array[departmentId]'");
                            $orderNo     = '';
                            $companyName = $department['name'];
                            break;
                        case '员工':
                            $staff       = query('staff', "stid = '$array[staffId]'");
                            $orderNo     = $staff['orderNo'];
                            $companyName = $staff['name'];
                            break;
                        default:
                            $orderNo     = '';
                            $companyName = '';
                            break;
                    }

                    $targetId    = match ($workFlow) {
                        '客户' => $array['khid'],
                        '供应商' => $array['supplierId'],
                        '员工' => $array['staffId'],
                        '部门' => $array['departmentId'],
                        '存货' => $array['materialId'],
                        '现金流' => $array['cashId'],
                        '项目' => $array['projectId'],
                    };
                    $initResult  = $this->initMoney($workFlow, $targetId, $startMonth, $subjectId);
                    $monthResult = $this->monthBalance($workFlow, $targetId, $startMonth, $endMonth, $subjectId);
                    $balance     = $this->balance($workFlow, $targetId, $endMonth, $subjectId);
                    $tr[]        = [$orderNo, $companyName, $initResult['jieMoney'], $initResult['daiMoney'], $monthResult['jieMoney'], $monthResult['daiMoney'], $balance['jieMoney'], $balance['daiMoney']];
                }
            } else {
                $title = array(
                    "辅助核算编码",
                    "辅助核算名称",
                    "借方期初数量",
                    '借方期初单价',
                    '借方期初金额',
                    '贷方期初数量',
                    '贷方期初单价',
                    '贷方期初金额',
                    '借方本期数量',
                    '借方本期单价',
                    '借方本期金额',
                    '贷方本期数量',
                    '贷方本期单价',
                    '贷方本期金额',
                    '借方期末数量',
                    '借方期末单价',
                    '借方期末金额',
                    '贷方期末数量',
                    '贷方期末单价',
                    '贷方期末金额'
                );
                //获取查询结果
                $all = sqlFind($sql);
                foreach ($all as $array) {
                    switch ($workFlow) {
                        case '客户':
                            $kehu        = query('kehu', "khid = '$array[khid]'");
                            $orderNo     = $kehu['orderNo'];
                            $companyName = $kehu['companyName'];
                            break;
                        case '供应商':
                            $supplier    = query('supplier', "id = '$array[supplierId]'");
                            $orderNo     = $supplier['code'];
                            $companyName = $supplier['name'];
                            break;
                        case '项目':
                            $project     = query('project', "id = '$array[projectId]'");
                            $orderNo     = $project['orderNo'];
                            $companyName = $project['name'];
                            break;
                        case '存货':
                            $material    = query('material', "id = '$array[materialId]'");
                            $orderNo     = $material['code'];
                            $companyName = $material['name'] . '-' . $material['model'];
                            break;
                        case '现金流':
                            $cash        = query('cash', "id = '$array[cashId]'");
                            $orderNo     = $cash['orderNo'];
                            $companyName = $cash['name'];
                            break;
                        case '部门':
                            $department  = query('department', "id = '$array[departmentId]'");
                            $orderNo     = $department['orderNo'];
                            $companyName = $department['name'];
                            break;
                        case '员工':
                            $staff       = query('staff', "stid = '$array[staffId]'");
                            $orderNo     = $staff['orderNo'];
                            $companyName = $staff['name'];
                            break;
                        default:
                            $orderNo     = '';
                            $companyName = '';
                            break;
                    }

                    $targetId    = match ($workFlow) {
                        '客户' => $array['khid'],
                        '供应商' => $array['supplierId'],
                        '员工' => $array['staffId'],
                        '部门' => $array['departmentId'],
                        '存货' => $array['materialId'],
                        '现金流' => $array['cashId'],
                        '项目' => $array['projectId'],
                    };
                    $initResult  = $this->initMoney($workFlow, $targetId, $startMonth, $subjectId);
                    $monthResult = $this->monthBalance($workFlow, $targetId, $startMonth, $endMonth, $subjectId);
                    $balance     = $this->balance($workFlow, $targetId, $endMonth, $subjectId);
                    $tr[]        = [
                        $orderNo,
                        $companyName,
                        $initResult['jieNum'],
                        $initResult['jiePrice'],
                        $initResult['jieMoney'],
                        $initResult['daiNum'],
                        $initResult['daiPrice'],
                        $initResult['daiMoney'],
                        $monthResult['jieNum'],
                        $monthResult['jiePrice'],
                        $monthResult['jieMoney'],
                        $monthResult['daiNum'],
                        $monthResult['daiPrice'],
                        $monthResult['daiMoney'],
                        $balance['jieNum'],
                        $balance['jiePrice'],
                        $balance['jieMoney'],
                        $balance['daiNum'],
                        $balance['daiPrice'],
                        $balance['daiMoney'],
                    ];
                }
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => $this->post('page'), "text" => $text]);
            $this->excelOut($title, $tr, self::title . ".xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

